<template>
    <!-- 弹窗 -->
    <div class="modal-overlay elResetBody" v-show="props.visible">
        <div class="modal-window" :class="{'modal-window-max':isMaximized}" ref="modalRef" :style="windowStyle">
            <div class="modal-header" @mousedown.stop.prevent="startDrag">
                <!-- 拖动手柄区域 -->                    
                <slot name="modalTitle">
                    <div class="modalTitle">
                        <svg-icon name="logo_itp" width="24px" />
                        <span>{{ title }}</span>
                    </div>
                </slot>
                <!-- 标题 -->
                    <div style="display: flex;">
                    <button @click.stop.prevent="maximize" class="button-resize">                            
                        <svg-icon name="office-maximize" width="8.5px" height="8.5px" color="var(--el-text-color-primary)" />
                    </button>
                    <button @click.stop.prevent="close" :class="[isDark ? 'button-close-dark' : 'button-close-light']">
                        <svg-icon name="office-close" width="10px" height="10px" color=var(--icon-color-close) />
                    </button>
                </div>
                <!-- 关闭按钮 -->
            </div>
            <div class="modal-body">
                <!-- 内容区域 -->  
                    <!-- 容器用于控制堆叠顺序 -->
                <div class="stack">
                    <slot name="modalBody"></slot>
                    <LoadingComponent v-if="props.isLoading" />
                </div>                
            </div>
            <div class="modal-foot">
                <slot name="modalFoot"></slot>
            </div>
            <!-- 调整大小的手柄 -->
            <div class="modal-resizer" @mousedown="startResize"></div>            
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onUnmounted } from 'vue';
import LoadingComponent from '@/components/ExceptionPage/LoadingComponent.vue';
const $emit = defineEmits(['update:visible','open']);
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: ''
    },
    initWidth:{
        type: String,
        default: '500px'
    },
    initHeight:{
        type: String,
        default: '300px'
    },
    isLoading:{
        type: Boolean,
        default: false
    }
})
const isDark = useDark()
const modalRef = ref<HTMLElement | null>(null);
const isDragging = ref(false);
const isResizing = ref(false);
const startPos = reactive({ x: 0, y: 0 });
const startOffSet = reactive({ x: 0, y: 0 });
const minWidth = '500px';
const minHeight = '300px';
const windowStyle = reactive({
    width: props.initWidth,
    height: props.initHeight,
    top: '100px',
    left: '0px'
});
const startSize = reactive({ x: parseFloat(windowStyle.width), y: parseFloat(windowStyle.height) });

const startDrag = (event: MouseEvent) => {
    if(isMaximized.value == false){
        isDragging.value = true;
        startPos.x = event.clientX;
        startPos.y = event.clientY;
        document.addEventListener('mousemove', doDrag);
        document.addEventListener('mouseup', stopDrag);
    }    
};

const startResize = (event: MouseEvent) => {
    if(isMaximized.value == false){
        isResizing.value = true;
        startPos.x = event.clientX;
        startPos.y = event.clientY;
        document.addEventListener('mousemove', doResize);
        document.addEventListener('mouseup', stopResize);
    }
};

const doDrag = (event: MouseEvent) => {    
    if (isDragging.value && modalRef.value) {
        const deltaX = event.clientX - startPos.x + startOffSet.x;
        const deltaY = event.clientY - startPos.y + startOffSet.y;
        const transformValue = `translate(${deltaX}px, ${deltaY}px)`;
        modalRef.value.style.transform = transformValue;
    }
};

const doResize = (event: MouseEvent) => {
    if (isResizing.value) {
        const width = 2*(event.clientX - startPos.x) + startSize.x;
        const height = event.clientY - startPos.y + startSize.y;
        windowStyle.width = `${width}px`;
        windowStyle.height = `${height}px`;
    }
};

const stopDrag = () => {    
    if (isDragging.value) {
        isDragging.value = false;
        if (modalRef.value) {
            // 获取 transform 的值
            const transform = modalRef.value.style.transform;
            // 提取移动后的 X 和 Y 位置
            const matches = /translate\((.+?)px, (.+?)px\)/.exec(transform);
            if (matches) {
                startOffSet.x = parseFloat(matches[1]);
                startOffSet.y = parseFloat(matches[2]);
            }
        }
        document.removeEventListener('mousemove', doDrag);
        document.removeEventListener('mouseup', stopDrag);
    }
};

const stopResize = () => {
    if (isResizing.value) {
        isResizing.value = false;
        startSize.x = parseFloat(windowStyle.width);
        startSize.y = parseFloat(windowStyle.height);
        document.removeEventListener('mousemove', doResize);
        document.removeEventListener('mouseup', stopResize);
    }
};

const close = () => {
    startPos.x = 0;
    startPos.y = 0;
    startOffSet.x = 0;
    startOffSet.y = 0;
    $emit('update:visible', false);
};


const handleEscape = (event: KeyboardEvent) => {
    if (event.key === 'Escape') {
        $emit('update:visible', false);
    }
};

const isMaximized = ref<boolean>(false);
let originWindowStyle = {
    width: windowStyle.width,
    height: windowStyle.height,
    top: windowStyle.top,
    left: windowStyle.left,
    transform: modalRef.value?.style.transform || 'translate(0px, 0px)'
};
const maximize = () => {    
    if(isMaximized.value == true){
        windowStyle.width = originWindowStyle.width;
        windowStyle.height = originWindowStyle.height;
        windowStyle.top = originWindowStyle.top;
        windowStyle.left = originWindowStyle.left;
        if(modalRef.value){
            modalRef.value.style.transform = originWindowStyle.transform;
        }
        isMaximized.value = false;
    }else{
        originWindowStyle = {
            width: windowStyle.width,
            height: windowStyle.height,
            top: windowStyle.top,
            left: windowStyle.left,
            transform: modalRef.value?.style.transform || 'translate(0px, 0px)'
        };
        isMaximized.value = true;
        windowStyle.width = '100vw';
        windowStyle.height = '100vh';
        windowStyle.top = '0px';
        windowStyle.left = '0px';
        if(modalRef.value){
            modalRef.value.style.transform = `translate(0px, 0px)`;   
        }
    }        
};
onMounted(() => {    
    window.addEventListener('keydown', handleEscape);
    // 监听 visible 属性的变化
    watch(() => props.visible, (newVisible) => {
        if (newVisible) {            
            $emit('open');
        }
    }); 
});

onUnmounted(() => {
    document.removeEventListener('mousemove', doDrag);
    document.removeEventListener('mouseup', stopDrag);
    document.removeEventListener('mousemove', doResize);
    document.removeEventListener('mouseup', stopResize);
    window.removeEventListener('keydown', handleEscape);
});
</script>
<style scoped lang="scss">
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(57, 57, 57, 0.5);
    display: flex;
    justify-content: center;
    align-items: top;
    z-index: 1000;
    --icon-color-close: #E84026;
}

.modal-window {
    background-color:var(--el-bg-color-overlay);
    border-radius: 12px;
    box-shadow: 0px 20px 60px 0px rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(0, 0, 0, 0.2);
    min-width: v-bind(minWidth);
    min-height: v-bind(minHeight);
    position: relative;
    // user-select: none;
    display: flex;
    flex-direction: column;
    .modal-body {
        display: flex;
        flex: 1;
        padding: 12px 12px 0 12px;
        overflow-y: auto;
    } 
    .modal-resizer {
        position: absolute;
        width: 10px;
        height: 10px;
        bottom: 0;
        right: 0;
        cursor: se-resize; // Southeast resize cursor
        // background-color: #f0f0f0;
        border-bottom-right-radius: 16px;
    }
}
.modal-window-max{
    border-radius: 0px;
}
.modal-header {    
    height: 50px;
    padding: 0 12px;  
    margin: 0 12px;  
    // border-bottom: 1px solid var(--el-border-color-light);
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    // background-color: rgb(247,248,251);

    .modalTitle{
        display: flex;
        align-items: center;
        // margin-left: 24px;
        span{
            margin-left: 12px;
            color: var(--el-text-color-primary);
            height: 24px;
            line-height: 24px;  
            font-size: 15px;                        
            font-weight: bold;
        }
    }

    button {
        background-color: transparent;
        border: none;
        cursor: pointer;
        border-radius: 12px;        
        display: flex;
        height: 24px;
        width: 24px;
        align-items: center;
        justify-content: center;        
    }
    .button-close-light{
        background-color: rgb(253,233,236); 
        &:hover {                                    
            background-color:var(--el-color-danger);
            --icon-color-close:#fff;
        }
    }
    .button-close-dark{
        background-color: var(--el-color-info-light-8); 
        &:hover {                                    
            background-color:var(--el-color-danger);
            --icon-color-close:#fff;
        }
    }
    .button-resize{
        margin-right: 12px;
        // background-color: rgb(232,232,232);
        background-color: var(--el-color-info-light-8);
        &:hover {                                    
            background-color:var(--el-color-info-light-5);         
        }
    }
}
::-webkit-scrollbar {    
    width: 15px;    
}
::-webkit-scrollbar-track {    
    border-radius: 8px;
}
.stack {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: 0; /* 容器的 z-index */
}
.stack > * {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

/* 确保 LoadingComponent 在最上层 */
.loading-container {
    z-index: 1; /* 加载中组件的 z-index 必须高于容器 */
}
</style>